import { uploadImg, saveSupervise } from '@/api/service/testApi.js'

// form表单
export function useForm() {
  const { userStore } = useStore()
  const orgcode = userStore.orgnow.orgnowcode
  const userId = userStore.user.id
  //提交操作
  const saveFormFn = (data) => {
    return new Promise((resolve) => {
      saveSupervise(
        {
          memberId: userId,
          orgcode: orgcode,
        },
        data
      ).then((res) => {
        resolve(res.errmsg)
      })
    })
  }

  return {
    saveFormFn,
  }
}

// 图片上传
export function useImgUpload() {
  const fileList = []
  const { userStore } = useStore()
  const orgcode = userStore.orgnow.orgnowcode

  // 上传操作
  const toUploadImg = (formdata) => {
    return new Promise((resolve) => {
      uploadImg(
        {
          orgcode: orgcode,
        },
        formdata
      ).then((res) => {
        resolve(res.result[0])
      })
    })
  }

  // van-uploader组件的上传钩子回调
  const afterRead = (file, detail) => {
    nextTick(() => {
      let formdata = new FormData() //new一个FormData
      formdata.append('file', file.file) //把上传的图片信息放入，传给后台
      toUploadImg(formdata).then((res) => {
        fileList[detail.index] = res
      })
    })
  }

  return {
    fileList,
    afterRead,
  }
}

// Rules验证
export function useRules() {
  const checkIdChard = (val) => {
    return DuUtil.isId(val)
  }
  const checkPhone = (val) => {
    return DuUtil.isMobile(val)
  }
  const titleRules = [
    { required: true, message: '举报主题不能为空' },
    {
      validator: (val) => val.length < 50,
      message: '举报主题文字过长',
    },
  ]
  const nameRules = [
    { required: true, message: '姓名不能为空' },
    {
      validator: (val) => val.length < 20,
      message: '姓名文字过长',
    },
  ]
  const idCardRules = [
    { required: true, message: '身份证号不能为空' },
    {
      validator: checkIdChard,
      message: '请输入正确的身份证号',
    },
  ]
  const phoneRules = [
    { required: true, message: '手机号码不能为空' },
    {
      validator: checkPhone,
      message: '请输入正确的手机号',
    },
  ]
  return {
    titleRules,
    nameRules,
    phoneRules,
    idCardRules,
  }
}
